package com.jueban.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jueban.Dto.*;
import com.jueban.Vo.ApplyOfIPVo;
import com.jueban.Vo.ApplyOfIPsVo;
import com.jueban.Vo.ResultVo;
import com.jueban.service.ApplyOfIPService;
import com.jueban.util.Messages;
import com.sun.istack.internal.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/api/applyOfIP")
public class ApplyOfIPController {

    private final ApplyOfIPService applyOfIPService;

    private final ObjectMapper objectMapper;

    @Autowired
    public ApplyOfIPController(ApplyOfIPService applyOfIPService, ObjectMapper objectMapper) {
        this.applyOfIPService = applyOfIPService;
        this.objectMapper = objectMapper;
    }


    // /api/applyOfIP GET获取申请
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ApplyOfIPVo getApplyOfIP(@PathVariable(value = "id") int id) {
        return applyOfIPService.getApplyOfIP(id);
    }


    // /api/applyOfIP DELETE删除一个申请
    @RequestMapping(value = "", method = RequestMethod.DELETE)
    public ResultVo deleteApplyOfIP(@RequestBody int id) {
        return applyOfIPService.deleteApplyOfIP(id);
    }


    // /api/applyOfIP POST 增加一个申请
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResultVo addApplyOfIP(@RequestParam("applyOfIPDto") String applyOfIPDto, @RequestParam("file") MultipartFile file) {
        ApplyOfIPDto applyOfIP = null;
        try {
            applyOfIP = objectMapper.readValue(applyOfIPDto, ApplyOfIPDto.class);
        } catch (IOException e) {
            System.out.println("json转换异常");
            e.printStackTrace();
        }
        return applyOfIPService.addApplyOfIP(applyOfIP, file);
    }


    @RequestMapping(value = "", method = RequestMethod.PUT)
    public ResultVo auditApply(@RequestBody @Valid SuggestAuditDto suggestAuditDto) {
        return applyOfIPService.auditApply(suggestAuditDto);
    }

    @RequestMapping(value = "/applyOfIPs", method = RequestMethod.POST)
    public ApplyOfIPsVo getAuditApply(@RequestBody @Valid ApplyOfIPQueryDto applyOfIPQueryDto) {
        Pageable pageable = new PageRequest(
                applyOfIPQueryDto.getOffset(), applyOfIPQueryDto.getPageSize());
        String queryType = applyOfIPQueryDto.getQueryType();

        //根据查询类型查询
        if (queryType.equals("teacher")) {
            return applyOfIPService.findTeacherApplyOfIP(pageable, applyOfIPQueryDto);
        } else if (queryType.equals("admin")) {
            return applyOfIPService.getAdminApplyOfIP(pageable, applyOfIPQueryDto);
        } else if (queryType.equals("self")) {
            return applyOfIPService.getSelfApplyOfIP(pageable, applyOfIPQueryDto);
        } else if (queryType.equals("manager")) {
            return applyOfIPService.getAdminApplyOfIP(pageable, applyOfIPQueryDto);
        }

        ApplyOfIPsVo applyOfIPsVo = new ApplyOfIPsVo();
        applyOfIPsVo.setFailed();
        applyOfIPsVo.setMessages(Messages.GET_FAIL);
        return applyOfIPsVo;
    }

    @RequestMapping(value = "/applyFile/pdf/{id}",method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> getApplyPdfFile(@PathVariable("id") int id) throws IOException{

        File file = applyOfIPService.getApplyOfIPApplyFile(id);
        if (file != null){
            String path = file.getPath();
            path = path.substring(0,path.lastIndexOf('.'));
            path = path +  ".pdf";
            return getResponseEntityByFilePath(path);
        }else {
            return null;
        }
    }

    @RequestMapping(value = "/applyFile/{id}", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> getApplyFile(@PathVariable("id") int id)
            throws IOException {
        String filePath = applyOfIPService.getApplyOfIPApplyFile(id).getPath();
        return getResponseEntityByFilePath(filePath);
    }

    @RequestMapping(value = "/proxyFile/{id}", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> getProxyFile(@PathVariable("id") int id) throws IOException {
        String filePath = applyOfIPService.getProxyFile(id).getPath();
        return getResponseEntityByFilePath(filePath);

    }

    @RequestMapping(value = "/auditFile/{id}", method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> getAuditFile(@PathVariable("id") int id) throws IOException {
        String filePath = applyOfIPService.getAuthorizedFile(id).getPath();
        return getResponseEntityByFilePath(filePath);
    }


    private ResponseEntity<InputStreamResource> getResponseEntityByFilePath(String filePath) throws IOException {
        FileSystemResource file = new FileSystemResource(filePath);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition"
                , "attachment; filename=" + "\"" + URLEncoder.encode(file.getFilename(), "utf-8") + "\"");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Mime-Type","application/pdf");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/pdf"))
                .body(new InputStreamResource(file.getInputStream()));
    }


    //录入代理通知书
    @RequestMapping(value = "/proxy", method = RequestMethod.POST)
    public ResultVo enterProxyFile(@RequestParam("proxyAudit") String proxyAudit, @RequestAttribute("file") MultipartFile file) {
        ProxyAuditDto proxyAuditDto = null;
        try {
            proxyAuditDto = objectMapper.readValue(proxyAudit, ProxyAuditDto.class);
        } catch (IOException e) {
            System.out.println("json转换异常");
            e.printStackTrace();
        }
        return applyOfIPService.enterProxyAudit(proxyAuditDto, file);
    }


    //录入授权信息
    @RequestMapping(value = "/auditFile", method = RequestMethod.POST)
    public ResultVo enterAuditFile(@RequestParam("authorize") String authorize, @RequestAttribute("file") @Nullable MultipartFile file) {
        AuthorizedDto authorizedDto = null;
        try {
            authorizedDto = objectMapper.readValue(authorize, AuthorizedDto.class);
        } catch (IOException e) {
            System.out.println("json转换异常");
            e.printStackTrace();
        }
        return applyOfIPService.enterAuthorizedFile(authorizedDto, file);
    }
  /*
    // 1 增加对知识产权申请的初审，加评语等API
    // /api/applyOfIP PUT 修改一个申请 （待定）
    @RequestMapping(value = "/departmentAudit", method = RequestMethod.POST)
    public ResultVo departmentAudit(@RequestBody @Valid DepartmentAuditDto departmentAuditDto) {
        return applyOfIPService.departmentAudit(departmentAuditDto);

    }

    @RequestMapping(value = "/managerAudit", method = RequestMethod.POST)
    public ResultVo managerAudit(@RequestBody @Valid SuggestAuditDto suggestAuditDto) {
        return applyOfIPService.managerAudit(suggestAuditDto);
    }

    @RequestMapping(value = "/academicAudit", method = RequestMethod.POST)
    public ResultVo academicAudit(@RequestBody @Valid SuggestAuditDto suggestAuditDto) {
        return applyOfIPService.academicAudit(suggestAuditDto);
    }*/

}
